# coding=utf-8
'''
Created on 2017年11月6日

@author: hhl
'''
import json
import requests
import urllib

SINA_API_KEY = '59955722'
SINA_API_SECRET = 'a74f24bc925468e15c9c6e0190ca23f1'

class SinaAuthSDK():
    """新浪授权调用
    """
    def __init__(self,api_key,api_secret):
        self.authorize = 'https://api.weibo.com/oauth2/authorize'
        self.app_key = api_key
        self.app_secret = api_secret
        self.token_url = 'https://api.weibo.com/oauth2/access_token?'
        self.get_info_url = 'https://api.weibo.com/2/users/show.json?'
    
    def dict2url(self, parms):
        parm_items = sorted(parms.items(), key=lambda d: d[0])
        parmlist = ["%s=%s"%item for item in parm_items]
        parm_str =  "&".join(parmlist)
        return parm_str
    
    def create_authorize_url(self, redirect_url):
        #授权链接
        parms = {'response_type':'code','client_id':self.app_key,'redirect_uri':'',
                'state':'1d2f3g4h5j6k','display':'default'}
        parms['redirect_uri'] = redirect_url#urllib.quote(redirect_url)
        params_str = self.dict2url(parms)
        url = '%s?%s'%(self.authorize,params_str)
        return url
    
    def get_token(self, code,redirect_url=''):
        token_params = {'grant_type':'authorization_code','code':code,
                        'client_id':self.app_key,
                        'client_secret':self.app_secret,'redirect_uri':redirect_url}
#         get_token_url = self.get_token_url(code, redirect_url)
#         print get_token_url
        result = requests.post(self.token_url, data=token_params) 
        print result
        data = result.json()
        print data
        return data
    
    def get_user_info(self,access_token,uid):
        user_info_url = '%saccess_token=%s&uid=%s'%(self.get_info_url,access_token,uid)
        print user_info_url
        result = requests.get(user_info_url)
        print result.text
        data = json.loads(result.text)
        return data
    
sinaclient = SinaAuthSDK(SINA_API_KEY, SINA_API_SECRET)

if __name__ == '__main__':
    url = 'http://h5.henkuai.com/auth/sina_auth'
    code = 'cbb3e47d37bb40f22cbb22dccdd82625'
    print sinaclient.create_authorize_url(url)
    token = '2.00nP_jVD0mNZDE47921981fdrPs_zB'
    uid = '3217263687'
#     print sinaclient.get_token(code,url)
#     print sinaclient.get_user_info(token,uid)